#include "PythonQtEnvManager.h"
#include <QApplication>
#include <QByteArray>
#include <QCoreApplication>
#include <QDebug>
#include <QDir>
#include <QFileInfo>
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
#include <QSharedPointer>
#include <QTextCodec>
#include <QVBoxLayout>
#include <QWidget>
#include <pybind11/pybind11.h>

int main(int argc, char *argv[]) {
  QApplication app(argc, argv);

  // 设置应用程序编码
  QTextCodec::setCodecForLocale(QTextCodec::codecForName("GBK"));

  // 初始化环境管理器
  auto envManager = ServerManager::getInstance().getDefaultPythonBindServer();
  if (!envManager->initialize()) {
    qCritical() << "Failed to initialize Python environment";
    return -1;
  }

  // 创建主窗口
  QWidget *mainWindow = new QWidget();
  mainWindow->setWindowTitle("PythonQtEnvManager Example");
  mainWindow->resize(400, 300);

  // 创建布局
  QVBoxLayout *layout = new QVBoxLayout(mainWindow);

  // 创建输入框1
  QLineEdit *input1 = new QLineEdit();
  input1->setObjectName("input1");
  input1->setPlaceholderText("输入框1");

  // 创建输入框2
  QLineEdit *input2 = new QLineEdit();
  input2->setObjectName("input2");
  input2->setPlaceholderText("输入框2");

  // 创建输入框3（只读）
  QLineEdit *input3 = new QLineEdit();
  input3->setObjectName("input3");
  input3->setPlaceholderText("结果将显示在这里");
  input3->setReadOnly(true);

  // 创建用于输入浮点数的输入框
  QLineEdit *floatInput = new QLineEdit();
  floatInput->setObjectName("floatInput");
  floatInput->setPlaceholderText("输入浮点数");

  // 创建按钮
  QPushButton *button = new QPushButton("执行Python脚本");
  button->setObjectName("executeButton");

  // 创建新按钮用于传递浮点数
  QPushButton *floatButton = new QPushButton("传递浮点数给Python");
  floatButton->setObjectName("floatButton");

  // 添加控件到布局
  layout->addWidget(new QLabel("输入框1:"));
  layout->addWidget(input1);
  layout->addWidget(new QLabel("输入框2:"));
  layout->addWidget(input2);
  layout->addWidget(button);
  layout->addWidget(new QLabel("输入框3 (结果):"));
  layout->addWidget(input3);
  layout->addWidget(new QLabel("浮点数输入:"));
  layout->addWidget(floatInput);
  layout->addWidget(floatButton);

  // 注册对象到环境管理器
  if (!envManager->registerObject(input1, "input1")) {
    qCritical() << "Failed to register input1";
    return -1;
  }

  if (!envManager->registerObject(input2, "input2")) {
    qCritical() << "Failed to register input2";
    return -1;
  }

  if (!envManager->registerObject(input3, "input3")) {
    qCritical() << "Failed to register input3";
    return -1;
  }

  if (!envManager->registerObject(floatInput, "floatInput")) {
    qCritical() << "Failed to register floatInput";
    return -1;
  }

  // 获取当前可执行文件的路径
  QString appPath = QCoreApplication::applicationDirPath();
  QString buttonScriptPath = appPath + "/button_script.py";
  QString mainScriptPath = appPath + "/example_script.py";

  // 检查脚本文件是否存在，如果不存在则使用源目录中的脚本
  QFileInfo buttonScriptInfo(buttonScriptPath);
  if (!buttonScriptInfo.exists()) {
    // 尝试使用源目录中的脚本
    buttonScriptPath = "examples/basic_usage/button_script.py";
    buttonScriptInfo.setFile(buttonScriptPath);
    if (!buttonScriptInfo.exists()) {
      qWarning() << "Button script file not found at:" << buttonScriptPath;
    }
  }

  // 为按钮注册对象并关联专用脚本
  if (!envManager->registerObject(button, "executeButton", buttonScriptPath)) {
    qWarning() << "Failed to register button with script:" << buttonScriptPath;
    // 即使脚本注册失败，我们仍然继续执行
  }

  // 为浮点数按钮注册对象
  if (!envManager->registerObject(floatButton, "floatButton",
                                  buttonScriptPath)) {
    qWarning() << "Failed to register floatButton with script:"
               << buttonScriptPath;
    // 即使脚本注册失败，我们仍然继续执行
  }

  // 注册主窗口
  if (!envManager->registerObject(mainWindow, "mainWindow")) {
    qWarning() << "Failed to register mainWindow";
    // 即使注册失败，我们仍然继续执行
  }

  // 连接按钮点击信号到Python脚本函数
  QObject::connect(button, &QPushButton::clicked, [&envManager]() {
    try {
      // 执行按钮关联脚本中的on_button_clicked函数
      pybind11::object result =
          envManager->executeFunction("executeButton", "on_button_clicked");

      // 正确处理UTF-8编码的字符串
      std::string resultStr = result.cast<std::string>();
      QString qResult = QString::fromUtf8(resultStr.c_str());
      qDebug().noquote() << "Python脚本执行结果:" << qResult;
    } catch (const std::exception &e) {
      qCritical() << "执行Python脚本时出错:" << e.what();
    }
  });

  // 连接浮点数按钮点击信号到Python脚本函数
  QObject::connect(floatButton, &QPushButton::clicked,
                   [&envManager, &floatInput]() {
                     try {
                       // 获取浮点数输入框的值
                       QString floatText = floatInput->text();
                       bool ok;
                       double floatValue = floatText.toDouble(&ok);

                       if (!ok) {
                         qCritical() << "输入的不是有效的浮点数";
                         return;
                       }

                       // 创建包含浮点数的参数元组
                       //  auto args = pybind11::make_tuple(floatValue);
                       pybind11::list args;
                       args.append(floatValue);

                       // 执行按钮关联脚本中的处理浮点数函数
                       pybind11::object result = envManager->executeFunction(
                           "floatButton", "process_float_value", args);

                       // 正确处理UTF-8编码的字符串
                       std::string resultStr = result.cast<std::string>();
                       // QByteArray qResult =
                       // QByteArray::fromStdString(resultStr);
                       // qDebug().noquote() << "Python脚本执行结果:" <<
                       // qResult.toHex()
                       //                    <<
                       //                    QString::fromUtf8(resultStr.c_str())
                       //                    <<
                       //                    QString::fromStdString(resultStr);
                       QString qResult = QString::fromUtf8(resultStr.c_str());
                       qDebug().noquote() << "Python脚本执行结果:" << qResult;
                     } catch (const std::exception &e) {
                       qCritical() << "执行Python脚本时出错:" << e.what();
                     }
                   });

  // 显示窗口
  mainWindow->show();

  int result = app.exec();

  // 清理资源
  envManager->unregisterObject("input1");
  envManager->unregisterObject("input2");
  envManager->unregisterObject("input3");
  envManager->unregisterObject("floatInput");
  envManager->unregisterObject("executeButton");
  envManager->unregisterObject("floatButton");
  envManager->unregisterObject("mainWindow");

  delete mainWindow;

  return result;
}